<template>
  <div class="create-order-container">
    <el-card class="order-form-card">
      <template #header>
        <div class="card-header">
          <h2>预订房间</h2>
        </div>
      </template>
      
      <div v-if="loading" class="loading-container">
        <el-skeleton :rows="5" animated />
      </div>
      
      <el-form v-else :model="form" :rules="rules" ref="formRef" label-width="100px">
        <el-divider content-position="left">酒店与房型信息</el-divider>
        
        <el-form-item label="酒店名称">
          <el-input v-model="form.hotelName" disabled />
        </el-form-item>
        
        <el-form-item label="房型">
          <el-input v-model="form.roomType" disabled />
        </el-form-item>
        
        <el-form-item label="价格">
          <el-input v-model="form.amount" disabled>
            <template #append>¥ / 晚</template>
          </el-input>
        </el-form-item>
        
        <el-form-item label="含早餐">
          <el-tag v-if="roomInfo?.breakfast === '1'" type="success">是</el-tag>
          <el-tag v-else>否</el-tag>
        </el-form-item>
        
        <el-divider content-position="left">订单信息</el-divider>
        
        <el-form-item label="用户ID" prop="userId">
          <el-input v-model="form.userId" :disabled="!!userInfoStore.userInfo?.user.userId" />
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" @click="submitForm" :loading="submitting">创建订单</el-button>
          <el-button @click="goBack">返回</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useUserInfoStore } from '@/stores/userInfo'
import { ElMessage } from 'element-plus'
import { createOrder } from '@/api/order'
import { getRoomsByHotel } from '@/api/room'

const route = useRoute()
const router = useRouter()
const userInfoStore = useUserInfoStore()
const formRef = ref(null)
const loading = ref(true)
const submitting = ref(false)
const roomInfo = ref(null)

// 表单数据
const form = reactive({
  userId: '',
  hotelName: '',
  roomType: '',
  amount: ''
})

// 表单验证规则
const rules = reactive({
  userId: [
    { required: true, message: '请输入用户ID', trigger: 'blur' }
  ]
})

// 初始化数据
const initData = async () => {
  loading.value = true
  
  try {
    let hotelName = '';
    let roomType = '';
    let isRebooking = false;
    
    // 检查是否从退房管理页面过来的续订操作
    const rebookInfoStr = sessionStorage.getItem('rebookInfo')
    
    if (rebookInfoStr) {
      try {
        // 如果是续订，从sessionStorage获取信息
        const rebookInfo = JSON.parse(rebookInfoStr)
        hotelName = rebookInfo.hotelName
        roomType = rebookInfo.roomType
        isRebooking = true
        
        // 使用后清除这个信息
        sessionStorage.removeItem('rebookInfo')
      } catch (e) {
        console.error('解析续订信息错误:', e)
      }
    } 
    
    // 如果不是续订或解析出错，从URL参数获取酒店名称和房型
    if (!isRebooking || !hotelName || !roomType) {
      hotelName = route.query.hotelName as string
      roomType = route.query.roomType as string
      
      if (!hotelName || !roomType) {
        ElMessage.error('缺少必要的参数')
        goBack()
        return
      }
    }
    
    // 设置表单默认值
    form.hotelName = hotelName
    form.roomType = roomType
    
    // 如果用户已登录，设置用户ID
    if (userInfoStore.userInfo?.user.userId) {
      form.userId = userInfoStore.userInfo.user.userId
    }
    
    // 获取房间信息（价格等）
    const res = await getRoomsByHotel(hotelName)
    const result = res.data
    
    if (result && result.code === 200 && Array.isArray(result.data)) {
      // 查找匹配的房间
      const room = result.data.find(r => r.roomType === roomType)
      
      if (room) {
        roomInfo.value = room
        form.amount = room.price
      } else {
        ElMessage.error('未找到指定房型')
        goBack()
      }
    } else {
      ElMessage.error('获取房间信息失败')
      goBack()
    }
  } catch (error) {
    console.error('初始化订单数据错误:', error)
    ElMessage.error('网络错误，请稍后重试')
    goBack()
  } finally {
    loading.value = false
  }
}

// 提交表单
const submitForm = () => {
  formRef.value.validate(async (valid) => {
    if (!valid) return
    
    submitting.value = true
    
    try {
      // 创建订单时不设置支付方式，将在后续支付步骤中选择
      const orderData = {
        userId: form.userId,
        hotelName: form.hotelName,
        roomType: form.roomType,
        amount: form.amount
      }
      
      const res = await createOrder(orderData)
      const result = res.data
      
      if (result && result.code === 200) {
        ElMessage.success('订单创建成功，请在订单列表中完成支付')
        router.push('/order')
      } else {
        ElMessage.error(result?.msg || '创建订单失败')
      }
    } catch (error) {
      console.error('创建订单错误:', error)
      ElMessage.error('网络错误，创建订单失败')
    } finally {
      submitting.value = false
    }
  })
}

// 返回上一页
const goBack = () => {
  router.back()
}

onMounted(() => {
  initData()
})
</script>

<style scoped>
.create-order-container {
  padding: 20px;
  max-width: 800px;
  margin: 0 auto;
}

.order-form-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.loading-container {
  padding: 20px;
}
</style> 